-module(permutate).

-compile(export_all).

-export([start/1]).

start([]) ->
    {ok,[]};
start(List) when is_list(List) ->
    {ok,[]};
start(_E) ->
    {error,_E}.

run([E]) ->
    [[E]];
run([Head|Rest]) ->
    lists:foldl( fun(LR,Acc) ->
			 gene_ins_list(Head,[],LR,[]) ++ Acc
		 end, [], run(Rest)).

gene_ins_list(E,Left,[],Ret) ->
    [Left ++ [E] | Ret];
gene_ins_list(E,Left,[H|Rest]=Right,Ret) ->
    gene_ins_list(E,Left ++ [H],Rest,[Left ++ [E] ++ Right|Ret]).


perms([]) ->
  [[]];
perms([X|Xs]) ->
    [ insert(X,As,Bs) || Ps <- perms(Xs), {As,Bs} <- splits(Ps) ].

splits([]) ->
    [{[],[]}];
splits([X|Xs] = Ys) ->
    [ {[],Ys} | [ { [X|As] , Bs} || {As,Bs} <- splits(Xs) ] ].

insert(X,As,Bs) ->
    lists:append([As,[X],Bs]).

